package cc.bluemc.modules.weixin.service;


import cc.bluemc.modules.weixin.entity.WxPublicAccountEntity;
import cc.bluemc.modules.weixin.entity.WxQrcordEntity;
import cc.bluemc.platform.comm.DataTablesPagination;
import cc.bluemc.platform.jdbctemplatetool.JdbcTemplateTool;
import cc.bluemc.platform.jdbctemplatetool.exception.NoColumnAnnotationFoundException;
import cc.bluemc.platform.jdbctemplatetool.exception.NoIdAnnotationFoundException;
import com.gson.bean.AuthorizationInfo;
import com.gson.bean.QrCodeInfo;
import com.gson.bean.WeixinAccount;
import com.gson.oauth.Authorize3p;
import com.gson.oauth.Qrcod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

/**
*WxQrcord service
*/
@Transactional(readOnly=true)
@Service("wxQrcordService")
public class WxQrcordService {
   	private Log log = LogFactory.getLog(this.getClass());
	@Autowired
	private JdbcTemplateTool jdbcTemplateTool;
	@Autowired
	private WxPublicAccountService accountService;


  	@Transactional(readOnly=false)
    public void save(WxQrcordEntity wxQrcord) throws Exception{
    	jdbcTemplateTool.save(wxQrcord);
    }
	@Transactional(readOnly=false)
    public int saveAndGetId(WxQrcordEntity wxQrcord) throws Exception{
    	return jdbcTemplateTool.save(wxQrcord,"id");
    }
	@Transactional(readOnly=false)
    public void update(WxQrcordEntity wxQrcord) throws Exception{
    	jdbcTemplateTool.update(wxQrcord);
    }
	@Transactional(readOnly=false)
    public void saveOrUpdate(WxQrcordEntity wxQrcord) throws Exception {
		Assert.notNull(wxQrcord);
		wxQrcord.setCreateTime(new Date());
		WxPublicAccountEntity accountEntity = accountService.get(wxQrcord.getAppid());
		if (null!=accountEntity) {
			QrCodeInfo scene =null;
			Qrcod qrcod = new Qrcod();
			WeixinAccount weixinAccount=WeixinAccount.getWeixinAccount();
			AuthorizationInfo authAccessToken
					=Authorize3p.getAuthAccessToken(weixinAccount, accountEntity.getAppid(), accountEntity.getAuthorizerRefreshToken());
			switch (wxQrcord.getActionName()){
				case QR_SCENE:
					scene =qrcod.createScene(authAccessToken.getAuthorizer_access_token(),
							wxQrcord.getExpireseconds(),
							Integer.parseInt(wxQrcord.getParam()));
					break;
				case QR_LIMIT_SCENE:
				case QR_LIMIT_STR_SCENE:
					scene =qrcod.createLimitScene(authAccessToken.getAuthorizer_access_token(),
							Integer.parseInt(wxQrcord.getParam()));
					break;
			}
			wxQrcord.setImgurl(scene.getImgUrl());
			wxQrcord.setUrl(scene.getUrl());
			wxQrcord.setTicket(scene.getTicket());
			wxQrcord.setExpireseconds(scene.getExpireSeconds());

			if (null == wxQrcord.getId() || 0 == wxQrcord.getId()) {
				save(wxQrcord);
			} else {
				update(wxQrcord);
			}
		}

    }

    public WxQrcordEntity get(Integer id) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
    	return jdbcTemplateTool.get(WxQrcordEntity.class, id);
    }
 	/**
     * 所有列表
     */
    public List<WxQrcordEntity> getAll() {
    	String sql="SELECT * FROM t_wx_qrcord ";
    	return jdbcTemplateTool.list(sql, null, WxQrcordEntity.class);
    }
    /**
     * 分页列表
     * @param page
     * @return
     */
    public DataTablesPagination getListOfPage(DataTablesPagination page,WxQrcordEntity wxQrcord){
    	StringBuffer sql = new StringBuffer(" FROM t_wx_qrcord WHERE 1=1 ");
    	List<Object> params = new ArrayList<Object>();
		if(null!=wxQrcord){
			if(StringUtils.isNotBlank(wxQrcord.getAppid())){
				sql.append("and appid=? ");
				params.add(wxQrcord.getAppid());
			}
		}
    	
    	int count =jdbcTemplateTool.count("SELECT count(0)"+sql, params.toArray());
    	page.setiTotalRecords(count);
    	
    	sql.append(" LIMIT ?,?");
    	params.add(page.getiDisplayStart());
    	params.add(page.getiDisplayLength());
    	List<WxQrcordEntity> list = jdbcTemplateTool.list("SELECT * "+sql, params.toArray(), WxQrcordEntity.class);
    	page.setData(list);
    	return page;
    }
     /**
     * 删除
     * @throws Exception
     */
	@Transactional(readOnly=false)
    public void delete(WxQrcordEntity wxQrcord) throws Exception {
   	 	jdbcTemplateTool.delete( wxQrcord);
    }

	public WxQrcordEntity getQrcode(String param,String appid) throws NoColumnAnnotationFoundException, NoIdAnnotationFoundException {
		String sql=" param=? AND appid=?";
		return jdbcTemplateTool.get(sql,new Object[]{param,appid},WxQrcordEntity.class);
	}
}
